import { create } from 'zustand';
import { localCache, sessionCache } from '@/utils/storage';
import { menus, features } from '../mock/menu';
import type { MainStore, TagType } from './type';

export const useMainStore = create<MainStore>((set) => ({
	theme: localCache.getItem('theme'),
	token: '',
	userInfo: {},
	userMenus: menus,
	featuresRoutes: features,
	headerTags: [],

	setTheme: (theme) => set({ theme }),
	// 储存headerTags
	addRouteToTags: (tag) => {
		set((state) => {
			const tags = [...state.headerTags];
			const find = tags.find((item) => item.path === tag.path);
			if (!find) {
				tags.push(tag);
				sessionCache.setItem('headerTags', tags);
			}
			return { headerTags: tags };
		});
	},
	// 修改tags
	updateHeaderTags: (list: MainStore['headerTags']) => {
		set({ headerTags: list });
	},

	// 获取缓存数据
	loadLocalStorage: () => {
		const token = localCache.getItem('token') ?? '';
		const userInfo = localCache.getItem('userInfo') ?? {};
		set({ token, userInfo });
	},

	getMenusStorage: () => {
		const userMenus = localCache.getItem<MainStore['userMenus']>('userMenus') ?? [];
		set({ userMenus });
	},
	getTagsStorage: () => {
		const headerTags = sessionCache.getItem<TagType[]>('headerTags') ?? [];
		const homeTag = headerTags.find((item) => item.path === '/home');
		if (!homeTag) {
			headerTags.unshift({ title: '首页', path: '/home' });
		}
		set({ headerTags });
	}
}));
